package com.haoting.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.haoting.oss.service.OssService;
import com.haoting.oss.utils.ConstantPropertiesUtils;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file,String folder){
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            String filename = file.getOriginalFilename();

            //在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            filename = folder+"/"+uuid+filename;
         //获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            //调用oss方法实现上传
            //第一个参数：Bucket名称
            //第二个参数：上传到oss文件路径和文件名称
            ossClient.putObject(bucketName,filename,inputStream);
            ossClient.shutdown();
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public void deleteFileAvatar(String imagename) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            //调用oss方法实现上传
            //第一个参数：Bucket名称
            //第二个参数：上传到oss文件路径和文件名称
            ossClient.deleteObject(bucketName,imagename);
            ossClient.shutdown();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
